import Vue from "Vue";
import VueRouter from "vue-router";
import routes from "./routes";
import store from "@/store";
Vue.use(VueRouter);

// router/index.js
// 导入网页加载进度条
import Nprogress from "nprogress";
import "nprogress/nprogress.css";
// 关闭进度条小圈
Nprogress.configure({ showSpinner: false });

const router = new VueRouter({
  routes,
});

// 全局（针对所有路由）前守卫
router.beforeEach((to, from, next) => {
  document.title = to.meta.title || "无忧购";
  Nprogress.start(); // 开启进度条
  let token = store.state.token;
  if (token) {
    if (to.path === "/login") {
      next({ path: from.path });
    } else {
      next();
    }
  } else {
    if (to.meta.isNeedToken) {
      next({ path: "/login", query: { redirect: to.fullPath } });
    } else {
      next();
    }
  }
});
// 全局（针对所有路由）后守卫
router.afterEach(() => {
  Nprogress.done(); // 关闭进度条
});

// 先保存原始的 VueRoute push方法的引用
const originPush = VueRouter.prototype.push;
const originReplace = VueRouter.prototype.replace;

// 后重写
VueRouter.prototype.push = function (location, okCallback, failCallback) {
  if (okCallback && failCallback) {
    return originPush.call(this, location, okCallback, failCallback);
  } else {
    return originPush.call(this, location).catch(() => {});
  }
};
VueRouter.prototype.replace = function (location, okCallback, failCallback) {
  if (okCallback && failCallback) {
    return originReplace.call(this, location, okCallback, failCallback);
  } else {
    return originReplace.call(this, location).catch(() => {});
  }
};

export default router;
